/* ldir.c */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "swis.h"


/***************************************************************************/

static char dir_name[256];

typedef struct {
  unsigned load;
  unsigned exec;
  int length;
  unsigned attributes;
  int object_type;
  unsigned sin;
  char timestamp[5];
  char name[12];
} DirEntry;

enum {
  FILE_OBJECT = 1,
  DIR_OBJECT = 2,
  IMAGE_OBJECT = 3
};

static DirEntry buff;


/***************************************************************************/

static void list_directory(void)

  /* lists the directory entries */

{
  int index = 0;
  int res;
  char timestamp[21];

  do
  {
    _swi(OS_GBPB, I0|I1|I2|I3|I4|I5|I6|O3|O4,
           11,                /* OS_GBPB 11 - read dir entries with SIN */
           (int)dir_name,     /* from this directory */
           (int)&buff,        /* into this buffer */
           1,                 /* one at a time */
           index,             /* starting with this one */
           sizeof(buff),      /* length of buffer */
           0,                 /* read all of them */
           &res,              /* set to number read - or -1 if none */
           &index             /* identifies next entry to read */
        );

    if (res == 1)             /* I expect this is always the case, but ... */
    {
     /* convert timestamp */
      if (*((int*)(buff.timestamp)) == 0 && buff.timestamp[4] == 0)
        strcpy(timestamp, "*** unstamped ***");
      else
        _swi(OS_ConvertDateAndTime, I0|I1|I2|I3,
               buff.timestamp,
               (int)timestamp,
               21,
               "%24:%mi:%se %dy-%m3-%yr"
            );

     /* list details */
      printf("%2d: %-10s %08x %08x %7d %08x %c %06x %s\n",
               index,
               &buff.name,
               buff.load, buff.exec,
               buff.length,
               buff.attributes,
               buff.object_type == FILE_OBJECT ? 'F' :
                 buff.object_type == DIR_OBJECT  ? 'D' :
                 buff.object_type == IMAGE_OBJECT ? 'P' : '?',
               buff.sin,
               timestamp); 
    }

  } while (index >= 0);       /* -1 => no more entries to read */

  return;
}

/***************************************************************************/

int main(int argc, char *argv[])

{
  if (argc != 2)
    strcpy(dir_name, "$");
  else
    strcpy(dir_name, argv[1]);

  printf(" n     name      load     exec    length   attr type SIN       timestamp\n");

  list_directory();

    
  return 0;
}

/***************************************************************************/
